package com.xiyi.shouxin.utils;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import com.xiyi.shouxin.conf.FileUploadConfig;
import com.xiyi.shouxin.exception.CommonException;
import com.xiyi.shouxin.exception.ErrorCode;

@Component
public class FileUtil {

    public String randomFileName() {
        return Long.toString(System.currentTimeMillis());
    }

    public String upload(MultipartFile file, String subPath) throws Exception {
        if (file.isEmpty()) {
            throw new CommonException(ErrorCode.INVALIDPARAMTER);
        }

        String fileName = file.getOriginalFilename();
        if (!StringUtils.hasText(fileName)) {
            fileName = file.getName();
            if (!StringUtils.hasText(fileName)) {
                fileName = randomFileName();
            }
        }
        Path path = Paths.get(FileUploadConfig.getBasePath(), subPath);
        if (!Files.exists(path)) {
            File dir = new File(path.toString());
            boolean result=dir.mkdirs();
            if (!result) {
                throw new CommonException(ErrorCode.INTERNAL);
            }
        }
        File f = new File(path.toAbsolutePath().toFile(), fileName);
        if (f.exists()) {
            boolean result=f.delete();
            if (!result) {
                throw new CommonException(ErrorCode.INTERNAL);
            }
        }
        file.transferTo(f);
        return FileUploadConfig.getBaseUrl()+subPath+"/"+fileName;
    }
}
